package cc.ucanuup.web.base.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.ucanuup.common.AppConsts;
import cc.ucanuup.common.support.base.Msg;
import cc.ucanuup.common.support.easyui.view.EasyuiPage;
import cc.ucanuup.config.security.util.AppUtil;
import cc.ucanuup.service.base.dto.MasterCodeDto;
import cc.ucanuup.service.base.entity.RelationRoleResource;
import cc.ucanuup.service.base.entity.UpResource;
import cc.ucanuup.service.base.entity.UpRole;
import cc.ucanuup.service.base.enums.MasterCodeType;
import cc.ucanuup.service.base.inter.MasterCodeService;
import cc.ucanuup.service.base.inter.RoleResourceService;
import cc.ucanuup.service.base.inter.UpResourceService;
import cc.ucanuup.service.base.inter.UpRoleService;
import cc.ucanuup.web.base.model.RoleModel;
import cc.ucanuup.web.base.model.SearchRolResModel;
import cc.ucanuup.web.base.model.SearchRoleModel;

/**
 * 文件名： cc.ucanuup.web.base.controller.UpRoleController.java
 * 作者：   WenBin
 * 日期：   2018年2月12日
 * 功能说明：
 * =========================================================
 * 修改记录：
 * 修改作者    日期      修改内容
 * =========================================================
 *  Copyright (c) 2010-2011 .All rights reserved.
 */
@Controller
@RequestMapping("/srm/role")
public class UpRoleController {

	@Resource
	private MasterCodeService masterCodeService;
	@Resource
	private UpRoleService  upRoleService;
	@Resource
	private UpResourceService  upResourceService;
	@Resource
	private RoleResourceService roleResourceService;
	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.menuPage
	 * @Description:角色页面
	 * @author: WenBin
	 * @date: 2017年10月14日
	 * @version: 1.0
	 * @return
	 * String
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping("/rolePage")
	//@RequiresPermissions(value = "role:rolePage")
	public String menuPage(){
		return "base/power/role/rolePage";
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.createOrUpdateRolePage
	 * @Description: 添加或者更新页面
	 * @author: WenBin
	 * @date: 2017年10月17日
	 * @version: 1.0
	 * @return
	 * String
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping("/createOrUpdateRolePage")
	//@RequiresPermissions(value = "role:rolePage")
	public String createOrUpdateRolePage(String id ,HttpServletRequest request){
		UpRole role = upRoleService.findOne(id==null ? "" : id);
		if(role == null){
			role = new UpRole();
		}
		List<MasterCodeDto> list = masterCodeService.findActiveMasterCodeDto(MasterCodeType.SYSTEM_ROLE_TYPE);
		request.setAttribute("role", role);
		request.setAttribute("roleType", list);
		return "base/power/role/createOrUpdateRole";
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.queryRole
	 * @Description:查询角色信息（分页）
	 * @author: WenBin
	 * @date: 2017年10月14日
	 * @version: 1.0
	 * @return
	 * Object
	 * @throws Exception
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping("/queryRole")
	@ResponseBody
	public Object queryRole(SearchRoleModel  searchRoleModel) throws Exception{
		Page<UpRole> page = upRoleService.queryRolesAndSortIt(searchRoleModel);
		return new EasyuiPage<UpRole>(page.getContent(), page.getTotalElements(), page.getNumber()+1);
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.queryResourceByFidAndRoleId
	 * @Description: 通过父id 和角色ID 查询资源
	 * @author: WenBin
	 * @date: 2017年10月16日
	 * @version: 1.0
	 * @param searchRoleModel
	 * @return
	 * Object
	 * @throws Exception
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping("/queryResourceByFidAndRoleId")
	@ResponseBody
	public Object queryResourceByFidAndRoleId(SearchRolResModel  searchRolResModel) throws Exception{
		Page<UpResource> page = upResourceService.queryResourceByFidAndRoleId(searchRolResModel);
		return new EasyuiPage<UpResource>(page.getContent(), page.getTotalElements(), page.getNumber()+1);
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.saveOrUpdateRole
	 * @Description: 添加或者更新角色信息
	 * @author: WenBin
	 * @date: 2017年10月17日
	 * @version: 1.0
	 * @param roleModel
	 * @param bindResult
	 * @param model
	 * @return
	 * @throws Exception
	 * Object
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping("/saveOrUpdateRole")
	@ResponseBody
	public Object saveOrUpdateRole(@Valid RoleModel  roleModel,BindingResult bindResult, Model model) throws Exception{
		if (bindResult.hasErrors()) {
			List<ObjectError> map =bindResult.getAllErrors();
			return new Msg(false,"50",map);
		}
		UpRole role = upRoleService.findOne(roleModel.getId() == null? "" :roleModel.getId());
		//	Company company = companyService.findOne(roleModel.getCompanyId());
		if(role == null){
			role = new UpRole();
			BeanUtils.copyProperties(roleModel,role );
			role.setStatus((long)AppConsts.STATUS_UNACTIVE);
			//role.setCompany(company);
			role = upRoleService.save(role);
		}else{
			BeanUtils.copyProperties(roleModel, role);
			//role.setCompany(company);
			//role.setUpdatedBy(AppUtil.getUserInfoContext().getUserId());
			role = upRoleService.save(role);
		}
		return new Msg();
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.deleteRole
	 * @Description: 删除角色信息
	 * @author: WenBin
	 * @date: 2017年10月17日
	 * @version: 1.0
	 * @param id
	 * @return
	 * Object
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value="/deleteRole")
	@ResponseBody
	public Object deleteRole(String id){
		UpRole role = upRoleService.findOne(id == null? "" :id);
		if(role!=null){
			role.setDeleted(AppConsts.DELETED_REMOVE);
			role = upRoleService.save(role);
		}else{
			return new Msg(false,"50","不存在该角色！");
		}
		return new Msg();
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.updateRoleStatus
	 * @Description: 变更角色状态
	 * @author: WenBin
	 * @date: 2017年10月17日
	 * @version: 1.0
	 * @param id
	 * @return
	 * Object
	 * @throws Exception
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value="/updateRoleStatus")
	@ResponseBody
	public Object updateRoleStatus(String id) throws Exception{
		UpRole role = upRoleService.findOne(id == null? "" :id);
		if(role!=null){
			if(role.getStatus() == 1){
				role.setStatus(0L);
			}else{
				role.setStatus(1L);
			}
			role = upRoleService.save(role);
		}else{
			return new Msg(false,"50","不存在该角色！");
		}
		return new Msg();
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.updateResourceStatus
	 * @Description: 更新资源和角色的关联状态信息
	 * @author: WenBin
	 * @date: 2017年10月17日
	 * @version: 1.0
	 * @param roleId
	 * @param resId
	 * @return
	 * Object
	 * @throws Exception
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value="/updateResourceStatus")
	@ResponseBody
	public Object updateResourceStatus(String roleId,String resId) throws Exception{
		if(StringUtils.isEmpty(resId)||StringUtils.isEmpty(roleId)){
			return new Msg(false,"50","传入角色ID 或 资源ID 异常");
		}
		RelationRoleResource  relation = roleResourceService.findOneByRoleIdAndResId(roleId, resId);
		if(relation!=null){
			roleResourceService.delete(relation);
		}else{
			relation = new RelationRoleResource();
			relation.setResourceId(resId);
			relation.setRoleId(roleId);
			roleResourceService.save(relation);
		}
		return new Msg();
	}

	/**
	 * @Method: com.bozhon.web.base.controller.RoleController.addRoleMenus
	 * @Description: 添加，更新 用户菜单信息
	 * @author: WenBin
	 * @date: 2017年10月18日
	 * @version: 1.0
	 * @param navIds
	 * @param roleId
	 * @return
	 * Object
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value="/addRoleMenus")
	@ResponseBody
	public Object addRoleMenus(String navIds , String roleId){
		upResourceService.updateRoleMenus(navIds.split(","), roleId, AppUtil.getSrmUserInfo().getUserAccount());
		return new Msg();
	}
}
